import axios from 'axios'
// import store from '@/store'
// import { Message, MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
const service = axios.create({
  baseURL: process.env.BASE_API,
  timeout: 15000,
  withCredentials: true // 允许携带cookie
})

service.interceptors.request.use(config => {
  if (getToken()) {
    config.headers.Authorization = getToken()
  }
  return config
}, error => {
  // console.log(error)
  // Promise.reject(error)
})

service.interceptors.response.use(response => {
  const res = response.data
  // console.log(res)
  if (res.code !== 200) {
    // 402:多ip登录; 401:其他客户端登录了;  400:Token 过期了;
    if (res.code === 402) {
      MessageBox.confirm('你已被登出，可以取消继续留在该页面，或者重新登录', '确定登出', {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        store.dispatch('FedLoginOut').then(() => {
          location.reload() // 为了重新实例化vue-router对象 避免bug
        })
      })
    } else {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })
    }
    return Promise.reject(new Error('error'))
  } else {
    return response.data
  }
})

export default service
